package zhjb.platform.module.blog.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import zhjb.platform.dao.DCriteriaPageSupport;
import zhjb.platform.module.blog.bean.BlogBase;
import zhjb.platform.module.blog.bean.BlogComment;
import zhjb.platform.module.blog.bean.BlogContent;
import zhjb.platform.module.blog.bean.ShowBlog;
import zhjb.platform.web.service.BaseService;

public class BlogService extends BaseService {
	/**
	 * 发布或者保存草稿
	 * 
	 * @param base
	 * @param content
	 * @throws Exception
	 */
	public void saveOrUpdate(BlogBase base, BlogContent content, int type) throws Exception {
		base.setUpdatetime(new Date());
		if (base.getId() == null || base.getId().trim().length() == 0) {
			// 新增
			base.setCreattime(new Date());
			base.setPublishstate(type);
			base.setDelstate(0);
			base.setEncryption(0);
			if (type == 1) {
				base.setPublishtime(new Date());
			}
			base.setTopblog(0);
			base.setViewcount(0);
			save(base, content);
		} else {
			// 更新
			List<BlogBase> baseList = dao.findAllByCriteria(DetachedCriteria.forClass(BlogBase.class).add(Restrictions.eq("id", base.getId())));
			if (baseList != null && !baseList.isEmpty()) {
				BlogBase blogBase = baseList.get(0);
				blogBase.setAuthor(base.getAuthor());
				blogBase.setTitle(base.getTitle());
				blogBase.setPublishstate(type);
				if (type == 1) {
					blogBase.setPublishtime(new Date());
				}
				content.setBaseId(base.getId());
				content.setAuthor(base.getAuthor());
				update(blogBase, content);
			}
		}
	}

	/**
	 * 保存数据
	 * 
	 * @param base
	 * @param content
	 */
	public void save(BlogBase base, BlogContent content) {
		dao.saveIObject(base);
		content.setBaseId(base.getId());
		content.setAuthor(base.getAuthor());
		dao.saveIObject(content);
	}

	/**
	 * 更新数据
	 * 
	 * @param base
	 * @param content
	 */
	public void update(BlogBase base, BlogContent content) {
		dao.updateIObject(base);
		dao.updateIObject(content);
	}

	/**
	 * 查询草稿
	 * 
	 * @return
	 */
	public List<BlogBase> findAllCG() {
		return dao.findAllByCriteria(DetachedCriteria.forClass(BlogBase.class).add(Restrictions.eq("publishstate", 0)).addOrder(Order.desc("creattime")));
	}

	/**
	 * 加载草稿
	 * 
	 * @param baseId
	 * @return
	 */
	public BlogBase loadCgBase(String baseId) {
		List<BlogBase> baseList = dao.findAllByCriteria(DetachedCriteria.forClass(BlogBase.class).add(Restrictions.eq("id", baseId)));
		return baseList != null && !baseList.isEmpty() ? baseList.get(0) : null;
	}

	/**
	 * 加载草稿内容
	 * 
	 * @param baseId
	 * @return
	 */
	public BlogContent loadCgContent(String baseId) {
		List<BlogContent> bcList = dao.findAllByCriteria(DetachedCriteria.forClass(BlogContent.class).add(Restrictions.eq("baseId", baseId)));
		return bcList != null && !bcList.isEmpty() ? bcList.get(0) : null;
	}

	/**
	 * 根据baseId找到博客基本属性，并且浏览次数+1
	 * 
	 * @param baseId
	 * @return
	 */
	public BlogBase show(String baseId) {
		List<BlogBase> baseList = dao.findAllByCriteria(DetachedCriteria.forClass(BlogBase.class).add(Restrictions.eq("id", baseId)));
		BlogBase result = baseList != null && !baseList.isEmpty() ? baseList.get(0) : null;
		if (result != null) {
			result.setViewcount(result.getViewcount() + 1);
			dao.updateIObject(result);
		}
		return result;
	}

	/**
	 * 根据baseId找到博客内容
	 * 
	 * @param baseId
	 * @return
	 */
	public BlogContent showContent(String baseId) {
		List<BlogContent> bcList = dao.findAllByCriteria(DetachedCriteria.forClass(BlogContent.class).add(Restrictions.eq("baseId", baseId)));
		return bcList != null && !bcList.isEmpty() ? bcList.get(0) : null;
	}

	/**
	 * 前台显示博客
	 * 
	 * @param page
	 * @param pageSize
	 * @return
	 */
	public DCriteriaPageSupport<ShowBlog> findShowBlog(int page, int pageSize) {
		List<ShowBlog> result = new ArrayList<ShowBlog>();
		DCriteriaPageSupport<BlogBase> baseList = dao.findPageByCriteria(DetachedCriteria.forClass(BlogBase.class).add(Restrictions.eq("publishstate", 1)).addOrder(Order.desc("creattime")), pageSize, page);
		long total = 0;
		Set<String> idSet = new HashSet<String>();
		if (baseList != null && !baseList.isEmpty()) {
			total = baseList.getTotalCount();
			for (BlogBase base : baseList) {
				idSet.add(base.getId());
			}
			List<BlogContent> bcList = dao.findAllByCriteria(DetachedCriteria.forClass(BlogContent.class).add(Restrictions.in("baseId", idSet)));
			for (BlogBase base : baseList) {
				ShowBlog blog = new ShowBlog();
				blog.setBase(base);
				for (BlogContent bc : bcList) {
					if (bc.getBaseId().equals(base.getId())) {
						blog.setContent(bc);
						String contentString = bc.getContent();
						Document doc = Jsoup.parseBodyFragment(contentString);
						Element body = doc.body();
						Elements eles = body.select("h3");
						if (eles != null && !eles.isEmpty()) {
							eles.get(0).remove();
						}
						Elements hrs = body.select("hr");
						for (Element ele : hrs) {
							ele.remove();
						}
						Elements uls = body.select("ul li");
						for (Element ele : uls) {
							ele.tagName("p");
						}
						Elements lis = body.select("li");
						for (Element ele : lis) {
							ele.tagName("p");
						}
						Elements divs = body.select("div");
						for (Element ele : divs) {
							ele.tagName("p");
						}
						Elements brs = body.select("br");
						for (Element ele : brs) {
							ele.tagName("p");
						}
						Elements pres = body.select("pre");
						for (Element ele : pres) {
							ele.tagName("p");
						}
						Elements pEles = body.select("p");
						int length = 0;
						for (Element ele : pEles) {
							String pText = ele.text();
							pText = pText.trim();
							if (length > 300) {
								if (ele != null && ele.html() != null && ele.html().length() > 0) {
									try {
										ele.remove();
									} catch (Exception r) {
									}
								}
							} else {
								Elements breles = ele.getAllElements();
								if (breles != null && !breles.isEmpty()) {
									for (Element br : breles) {
										if (length > 300) {
											if (br != null && br.html() != null && br.html().length() > 0) {
												try {
													br.remove();
												} catch (Exception r) {
												}
											}
										} else {
											pText = br.text();
											length = length + pText.length();
											if (length > 300 * 2) {
												br.text(pText.substring(0, pText.length() > 300 ? 300 : pText.length()));
											}
											br.removeAttr("style");
											br.removeAttr("class");
										}
									}
								}
								ele.removeAttr("style");
								ele.removeAttr("class");
							}
						}
						contentString = body.html();
						blog.setShowContent(contentString);
						break;
					}
				}
				result.add(blog);
			}
		}
		DCriteriaPageSupport<ShowBlog> logResult = new DCriteriaPageSupport<ShowBlog>(result, total);
		return logResult;
	}

	/**
	 * 找到博客基本属性list
	 * 
	 * @param page
	 * @param pageSize
	 * @return
	 */
	public List<BlogBase> blogBaseList(int page, int pageSize) {
		List<BlogBase> blogBaseList = dao.findPageByCriteria(DetachedCriteria.forClass(BlogBase.class), pageSize, page);
		return blogBaseList;
	}

	/**
	 * 添加评论
	 * 
	 * @param content
	 * @param userIp
	 * @param blogId
	 */
	public void addCommont(String content, String userIp, String blogId) {
		BlogComment commont = new BlogComment();
		commont.setBlogId(blogId);
		commont.setComment(content);
		commont.setCreateDate(new Date());
		commont.setUserIp(userIp);
		dao.saveIObject(commont);
	}

	/**
	 * 删除博客
	 * 
	 * @param id
	 */
	public void deleteBolg(String id) {
		String hql = "update BlogBase set delstate=1 where id='" + id + "'";
		dao.execByHQL(hql);
	}

}
